<template>
    <div class="messageBox-root" ref="messageBox_dom">

    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const messageBox_dom = ref();
const massageArr = ref([]);
let messageIndex = 0;

const defAttr = () => ({
    text: 'NULL',
    color: 'default',
    time: 3000,
});

onMounted(() => {
    messageIndex = 0;
    massageArr.value = [];
    messageBox_dom.value.innerHTML = '';
})

const add = (data) => {
    let cur = {};
    Object.assign(cur, defAttr(), data);
    massageArr.value.push(cur);
    // massageArr.value.unshift(cur);
    cur.index = messageIndex++;

    add_Event(cur);
}

const add_Event = (data) => {
    // messageBox_dom
    const div = document.createElement('div');
    div.className = `message-item ${data.color}`;

    const span = document.createElement('span');
    span.innerHTML = data.text;

    div.append(span);

    messageBox_dom.value.append(div);
    setTimeout(() => {
        div.style.height = '31px';
    }, 100);
    if (data.time > 0) {
        setTimeout(() => {
            div.style.height = '0px';
            setTimeout(() => {
                massageArr.value = massageArr.value.filter(u => u.index != data.index);
                div.remove();
            }, 300);
        }, data.time + 100);
    }
};


defineExpose({
    add,
});
</script>

<style lang="scss">
.messageBox-root {
    // background: red;

    .message-item {
        margin: 7px;
        display: flex;
        flex-direction: row-reverse;
        overflow: hidden;
        height: 0;
        transition-duration: 0.3s;

        >span {
            padding: 5px 15px;
            border-radius: 5px;
            text-align: right;
        }
    }

    .message-item-show {
        height: 31px;
        opacity: 1;
    }

    .default {
        >span {
            background: #909399;
            color: white;
        }
    }

    .blue {
        >span {
            background: #409eff;
            color: white;
        }
    }

    .green {
        >span {
            background: #67c23a;
            color: white;
        }
    }

    .yellow {
        >span {
            background: #e6a23c;
            color: white;
        }
    }

    .red {
        >span {
            background: #f56c6c;
            color: white;
        }
    }
}
</style>